<template>
  <div class="app-container simple-app-container">
    <div v-permission="['purchase:return:add']" v-loading="loading">
      <j-border>
        <j-form>
          <j-form-item label="仓库" required>
            <store-center-selector
              v-model="formData.scId"
            />
          </j-form-item>
          <j-form-item label="供应商" required>
            <supplier-selector
              v-model="formData.supplierId"
              @input="supplierChange"
            />
          </j-form-item>
          <j-form-item label="采购员">
            <user-selector
              v-model="formData.purchaserId"
            />
          </j-form-item>
          <j-form-item label="付款日期" required>
            <a-date-picker
              v-model="formData.paymentDate"
              placeholder=""
              value-format="YYYY-MM-DD"
              :disabled="!formData.allowModifyPaymentDate"
              :disabled-date="(current) => {
                return current && current < moment().endOf('day');
              }"
            />
          </j-form-item>
          <j-form-item label="采购收货单">
            <receive-sheet-selector
              v-model="formData.receiveSheetId"
              @input="receiveSheetChange"
            />
          </j-form-item>
        </j-form>
      </j-border>
      <!-- 数据列表 -->
      <vxe-grid
        ref="grid"
        resizable
        show-overflow
        highlight-hover-row
        keep-source
        row-id="id"
        height="500"
        :data="tableData"
        :columns="tableColumn"
        :toolbar-config="toolbarConfig"
      >
        <!-- 工具栏 -->
        <template v-slot:toolbar_buttons>
          <a-space>
            <a-button type="primary" icon="plus" @click="addProduct">新增</a-button>
            <a-button type="danger" icon="delete" @click="delProduct">删除</a-button>
            <a-button icon="plus" @click="openBatchAddProductDialog">批量添加商品</a-button>
            <a-button icon="number" @click="batchInputReturnNum">批量录入数量</a-button>
            <a-button icon="edit" @click="batchInputPurchasePrice">批量调整采购价</a-button>
            <a-button icon="alert" @click="setGift">设置赠品</a-button>
          </a-space>
        </template>

        <!-- 商品名称 列自定义内容 -->
        <template v-slot:productName_default="{ row, rowIndex }">
          <a-auto-complete
            v-model="row.productName"
            style="width: 100%;"
            placeholder=""
            value-key="productName"
            @search="e => queryProduct(e, row)"
            @select="e => handleSelectProduct(rowIndex, e, row)"
          >
            <template slot="dataSource">
              <a-select-option v-for="(item, index) in row.products" :key="index" :value="item.productId">
                {{ item.productCode }} {{ item.productName }}
              </a-select-option>
            </template>
          </a-auto-complete>
        </template>

        <!-- 采购价 列自定义内容 -->
        <template v-slot:purchasePrice_default="{ row }">
          <span v-if="row.isGift">{{ row.purchasePrice }}</span>
          <a-input v-else v-model="row.purchasePrice" class="number-input" @input="e => purchasePriceInput(e.target.value)" />
        </template>

        <!-- 库存数量 列自定义内容 -->
        <template v-slot:stockNum_default="{ row }">
          <span v-if="checkStockNum(row)">{{ row.stockNum }}</span>
          <span v-else style="color: #F5222D;">{{ row.stockNum }}</span>
        </template>

        <!-- 退货数量 列自定义内容 -->
        <template v-slot:returnNum_default="{ row }">
          <a-input v-model="row.returnNum" class="number-input" @input="e => returnNumInput(e.target.value)" />
        </template>

        <!-- 含税金额 列自定义内容 -->
        <template v-slot:taxAmount_default="{ row }">
          <span v-if="$utils.isFloatGeZero(row.purchasePrice) && $utils.isIntegerGeZero(row.returnNum)">{{ $utils.mul(row.purchasePrice, row.returnNum) }}</span>
        </template>

        <!-- 备注 列自定义内容 -->
        <template v-slot:description_default="{ row }">
          <a-input v-model="row.description" />
        </template>
      </vxe-grid>

      <j-border title="合计">
        <j-form label-width="140px">
          <j-form-item label="退货数量" :span="6">
            <a-input v-model="formData.totalNum" class="number-input" read-only />
          </j-form-item>
          <j-form-item label="赠品数量" :span="6">
            <a-input v-model="formData.giftNum" class="number-input" read-only />
          </j-form-item>
          <j-form-item label="含税总金额" :span="6">
            <a-input v-model="formData.totalAmount" class="number-input" read-only />
          </j-form-item>
        </j-form>
      </j-border>

      <j-border>
        <j-form label-width="140px">
          <j-form-item label="备注" :span="24" :content-nest="false">
            <a-textarea v-model.trim="formData.description" maxlength="200" />
          </j-form-item>
        </j-form>
      </j-border>

      <batch-add-product
        ref="batchAddProductDialog"
        :sc-id="formData.scId"
        @confirm="batchAddProduct"
      />
      <div style="text-align: center; background-color: #FFFFFF;padding: 8px 0;">
        <a-space>
          <a-button v-permission="['purchase:return:add']" type="primary" :loading="loading" @click="createOrder">保存</a-button>
          <a-button v-permission="['purchase:return:approve']" type="primary" :loading="loading" @click="directApprovePassOrder">审核通过</a-button>
          <a-button :loading="loading" @click="closeDialog">关闭</a-button>
        </a-space>
      </div>
    </div>
  </div>
</template>
<script>
import StoreCenterSelector from '@/components/Selector/StoreCenterSelector'
import SupplierSelector from '@/components/Selector/SupplierSelector'
import UserSelector from '@/components/Selector/UserSelector'
import ReceiveSheetSelector from './ReceiveSheetSelector'
import BatchAddProduct from '@/views/sc/purchase/batch-add-product'
import Moment from 'moment'
export default {
  name: 'AddPurchaseReturnUnRequire',
  components: {
    StoreCenterSelector, SupplierSelector, UserSelector, ReceiveSheetSelector, BatchAddProduct
  },
  data() {
    return {
      // 是否显示加载框
      loading: false,
      // 表单数据
      formData: {},
      // 工具栏配置
      toolbarConfig: {
        // 缩放
        zoom: false,
        // 自定义表头
        custom: false,
        // 右侧是否显示刷新按钮
        refresh: false,
        // 自定义左侧工具栏
        slots: {
          buttons: 'toolbar_buttons'
        }
      },
      // 列表数据配置
      tableColumn: [
        { type: 'checkbox', width: 40 },
        { field: 'productCode', title: '商品编号', width: 120 },
        { field: 'productName', title: '商品名称', width: 260, slots: { default: 'productName_default' }},
        { field: 'skuCode', title: '商品SKU编号', width: 120 },
        { field: 'externalCode', title: '商品外部编号', width: 120 },
        { field: 'unit', title: '单位', width: 80 },
        { field: 'spec', title: '规格', width: 80 },
        { field: 'categoryName', title: '商品类目', width: 120 },
        { field: 'brandName', title: '商品品牌', width: 120 },
        { field: 'isGift', title: '是否赠品', width: 80, formatter: ({ cellValue }) => { return cellValue ? '是' : '否' } },
        { field: 'purchasePrice', title: '采购价（元）', align: 'right', width: 120, slots: { default: 'purchasePrice_default' }},
        { field: 'taxCostPrice', title: '含税成本价（元）', align: 'right', width: 140 },
        { field: 'stockNum', title: '库存数量', align: 'right', width: 100, slots: { default: 'stockNum_default' }},
        { field: 'returnNum', title: '退货数量', align: 'right', width: 100, slots: { default: 'returnNum_default' }},
        { field: 'taxAmount', title: '含税金额', align: 'right', width: 120, slots: { default: 'taxAmount_default' }},
        { field: 'taxRate', title: '税率（%）', align: 'right', width: 100 },
        { field: 'description', title: '备注', width: 200, slots: { default: 'description_default' }}
      ],
      tableData: []
    }
  },
  computed: {
    moment() {
      return Moment
    }
  },
  created() {
    // 初始化表单数据
    this.openDialog()
  },
  methods: {
    // 打开对话框 由父页面触发
    openDialog() {
      // 初始化表单数据
      this.initFormData()
    },
    // 关闭对话框
    closeDialog() {
      this.$utils.closeCurrentPage(this.$parent)
    },
    // 初始化表单数据
    async initFormData() {
      this.formData = {
        scId: '',
        supplierId: '',
        receiveSheetId: '',
        purchaserId: '',
        paymentDate: this.$utils.formatDate(Moment().add(1, 'M')),
        totalNum: 0,
        giftNum: 0,
        totalAmount: 0,
        description: '',
        // 是否允许修改付款日期
        allowModifyPaymentDate: true
      }

      this.tableData = []
    },
    emptyProduct() {
      return {
        id: this.$utils.uuid(),
        productId: '',
        productCode: '',
        productName: '',
        skuCode: '',
        externalCode: '',
        unit: '',
        spec: '',
        categoryName: '',
        brandName: '',
        purchasePrice: '',
        taxCostPrice: '',
        stockNum: '',
        returnNum: '',
        taxRate: '',
        isGift: false,
        taxAmount: '',
        description: '',
        isFixed: false,
        products: []
      }
    },
    // 新增商品
    addProduct() {
      if (this.$utils.isEmpty(this.formData.scId)) {
        this.$msg.error('请先选择仓库！')
        return
      }
      this.tableData.push(this.emptyProduct())
    },
    // 搜索商品
    queryProduct(queryString, row) {
      if (this.$utils.isEmpty(queryString)) {
        row.products = []
        return
      }

      this.$api.sc.purchase.purchaseOrder.searchProduct(this.formData.scId, queryString).then(res => {
        row.products = res
      })
    },
    // 选择商品
    handleSelectProduct(index, value, row) {
      this.tableData[index] = Object.assign(this.tableData[index], row ? row.products.filter(item => item.productId === value)[0] : value, {
        isGift: false
      })

      this.purchasePriceInput(this.tableData[index], this.tableData[index].purchasePrice)
    },
    // 删除商品
    delProduct() {
      const records = this.$refs.grid.getCheckboxRecords()
      if (this.$utils.isEmpty(records)) {
        this.$msg.error('请选择要删除的商品数据！')
        return
      }

      this.$msg.confirm('是否确定删除选中的商品？').then(() => {
        const tableData = this.tableData.filter(t => {
          const tmp = records.filter(item => item.id === t.id)
          return this.$utils.isEmpty(tmp)
        })

        this.tableData = tableData

        this.calcSum()
      })
    },
    openBatchAddProductDialog() {
      if (this.$utils.isEmpty(this.formData.scId)) {
        this.$msg.error('请先选择仓库！')
        return
      }
      this.$refs.batchAddProductDialog.openDialog()
    },
    purchasePriceInput(row, value) {
      this.calcSum()
    },
    returnNumInput(value) {
      this.calcSum()
    },
    // 计算汇总数据
    calcSum() {
      let totalNum = 0
      let giftNum = 0
      let totalAmount = 0

      this.tableData.filter(t => {
        return this.$utils.isFloatGeZero(t.purchasePrice) && this.$utils.isIntegerGeZero(t.returnNum)
      }).forEach(t => {
        const num = parseInt(t.returnNum)
        if (t.isGift) {
          giftNum = this.$utils.add(giftNum, num)
        } else {
          totalNum = this.$utils.add(totalNum, num)
        }

        totalAmount = this.$utils.add(totalAmount, this.$utils.mul(num, t.purchasePrice))
      })

      this.formData.totalNum = totalNum
      this.formData.giftNum = giftNum
      this.formData.totalAmount = totalAmount
    },
    // 批量录入数量
    batchInputReturnNum() {
      const records = this.$refs.grid.getCheckboxRecords()
      if (this.$utils.isEmpty(records)) {
        this.$msg.error('请选择商品数据！')
        return
      }

      this.$msg.prompt('请输入退货数量', {
        inputPattern: this.$utils.PATTERN_IS_INTEGER_GT_ZERO,
        inputErrorMessage: '退货数量必须为整数并且大于0',
        title: '批量录入数量'
      }).then(({ value }) => {
        records.forEach(t => {
          t.returnNum = value

          this.returnNumInput(value)
        })
      })
    },
    // 批量录入采购价
    batchInputPurchasePrice() {
      const records = this.$refs.grid.getCheckboxRecords()
      if (this.$utils.isEmpty(records)) {
        this.$msg.error('请选择商品数据！')
        return
      }

      for (let i = 0; i < records.length; i++) {
        if (records[i].isGift) {
          this.$msg.error('第' + (i + 1) + '行商品为赠品，不允许录入采购价！')
          return
        }
      }

      this.$msg.prompt('请输入采购价（元）', {
        inputPattern: this.$utils.PATTERN_IS_PRICE,
        inputErrorMessage: '采购价（元）必须为数字并且不小于0',
        inputValue: '0.00',
        title: '批量调整采购价'
      }).then(({ value }) => {
        records.forEach(t => {
          t.purchasePrice = value

          this.purchasePriceInput(t, value)
        })
      })
    },
    // 设置赠品
    setGift() {
      const records = this.$refs.grid.getCheckboxRecords()
      if (this.$utils.isEmpty(records)) {
        this.$msg.error('请选择要设置为赠品的商品数据！')
        return
      }

      records.forEach(item => {
        item.purchasePrice = 0
        item.isGift = true
      })

      this.calcSum()
    },
    // 批量新增商品
    batchAddProduct(productList) {
      productList.forEach(item => {
        this.tableData.push(this.emptyProduct())
        this.handleSelectProduct(this.tableData.length - 1, item)
      })
    },
    // 校验数据
    validData() {
      if (this.$utils.isEmpty(this.formData.scId)) {
        this.$msg.error('仓库不允许为空！')
        return false
      }

      if (this.$utils.isEmpty(this.formData.supplierId)) {
        this.$msg.error('供应商不允许为空！')
        return false
      }

      if (this.formData.allowModifyPaymentDate) {
        if (this.$utils.isEmpty(this.formData.paymentDate)) {
          this.$msg.error('付款日期不允许为空！')
          return false
        }
      }

      if (this.$utils.isEmpty(this.tableData)) {
        this.$msg.error('请录入商品！')
        return false
      }

      for (let i = 0; i < this.tableData.length; i++) {
        const product = this.tableData[i]

        if (this.$utils.isEmpty(product.productId)) {
          this.$msg.error('第' + (i + 1) + '行商品不允许为空！')
          return false
        }

        if (this.$utils.isEmpty(product.purchasePrice)) {
          this.$msg.error('第' + (i + 1) + '行商品采购价不允许为空！')
          return false
        }

        if (!this.$utils.isFloat(product.purchasePrice)) {
          this.$msg.error('第' + (i + 1) + '行商品采购价必须为数字！')
          return false
        }

        if (product.isGift) {
          if (parseFloat(product.purchasePrice) !== 0) {
            this.$msg.error('第' + (i + 1) + '行商品采购价必须等于0！')
            return false
          }
        } else {
          if (!this.$utils.isFloatGtZero(product.purchasePrice)) {
            this.$msg.error('第' + (i + 1) + '行商品采购价必须大于0！')
            return false
          }
        }

        if (!this.$utils.isNumberPrecision(product.purchasePrice, 2)) {
          this.$msg.error('第' + (i + 1) + '行商品采购价最多允许2位小数！')
          return false
        }

        if (!this.$utils.isEmpty(product.returnNum)) {
          if (!this.$utils.isInteger(product.returnNum)) {
            this.$msg.error('第' + (i + 1) + '行商品退货数量必须为整数！')
            return false
          }

          if (!this.$utils.isIntegerGtZero(product.returnNum)) {
            this.$msg.error('第' + (i + 1) + '行商品退货数量必须大于0！')
            return false
          }
        } else {
          this.$msg.error('第' + (i + 1) + '行商品退货数量不允许为空！')
          return false
        }
      }

      return true
    },
    // 创建订单
    createOrder() {
      if (!this.validData()) {
        return
      }

      const params = {
        scId: this.formData.scId,
        supplierId: this.formData.supplierId,
        purchaserId: this.formData.purchaserId || '',
        paymentDate: this.formData.paymentDate || '',
        description: this.formData.description,
        required: false,
        products: this.tableData.filter(t => this.$utils.isIntegerGtZero(t.returnNum)).map(t => {
          const product = {
            productId: t.productId,
            purchasePrice: t.purchasePrice,
            returnNum: t.returnNum,
            description: t.description
          }

          return product
        })
      }

      this.loading = true
      this.$api.sc.purchase.purchaseReturn.createOrder(params).then(res => {
        this.$msg.success('保存成功！')

        this.$emit('confirm')
        this.closeDialog()
      }).finally(() => {
        this.loading = false
      })
    },
    // 直接审核通过订单
    directApprovePassOrder() {
      if (!this.validData()) {
        return
      }

      const checkStockNumArr = []
      this.tableData.filter(item => this.$utils.isIntegerGtZero(item.returnNum)).forEach(item => {
        if (checkStockNumArr.map(v => item.productId).includes(item.productId)) {
          checkStockNumArr.filter(v => v.productId === item.productId).forEach(v => {
            v.returnNum = this.$utils.add(v.returnNum, item.returnNum)
          })
        } else {
          checkStockNumArr.push({
            productId: item.productId,
            productCode: item.productCode,
            productName: item.productName,
            stockNum: item.stockNum,
            returnNum: item.returnNum
          })
        }
      })

      const unValidStockNumArr = checkStockNumArr.filter(item => item.stockNum < item.returnNum)
      if (!this.$utils.isEmpty(unValidStockNumArr)) {
        this.$msg.error('商品（' + unValidStockNumArr[0].productCode + '）' + unValidStockNumArr[0].productName + '当前库存为' + unValidStockNumArr[0].stockNum + '，总退货数量为' + unValidStockNumArr[0].returnNum + '，无法完成采购退货！')
        return false
      }

      const params = {
        scId: this.formData.scId,
        supplierId: this.formData.supplierId,
        purchaserId: this.formData.purchaserId || '',
        paymentDate: this.formData.paymentDate || '',
        description: this.formData.description,
        products: this.tableData.filter(t => this.$utils.isIntegerGtZero(t.returnNum)).map(t => {
          const product = {
            productId: t.productId,
            purchasePrice: t.purchasePrice,
            returnNum: t.returnNum,
            description: t.description
          }

          return product
        })
      }

      this.$msg.confirm('对采购退货单执行审核通过操作？').then(() => {
        this.loading = true
        this.$api.sc.purchase.purchaseReturn.directApprovePassOrder(params).then(res => {
          this.$msg.success('审核通过！')

          this.$emit('confirm')
          this.closeDialog()
        }).finally(() => {
          this.loading = false
        })
      })
    },
    // 选择采购收货单
    receiveSheetChange(e) {
      // 只要选择了采购收货单，清空所有商品，然后将采购收货单中所有的明细列出来
      if (!this.$utils.isEmpty(e)) {
        this.loading = true
        this.$api.sc.purchase.receiveSheet.getWithReturn(e).then(res => {
          let receiveSheetDetails = res.details || []
          receiveSheetDetails = receiveSheetDetails.map(item => {
            item.isFixed = false

            return Object.assign(this.emptyProduct(), item)
          })

          this.tableData = receiveSheetDetails

          this.formData.scId = res.scId

          this.formData.supplierId = res.supplierId

          if (!this.$utils.isEmpty(res.purchaserId)) {
            this.formData.purchaserId = res.purchaserId
          }

          this.supplierChange(this.formData.supplierId)
        }).finally(() => {
          this.loading = false
        })
      }
    },
    // 供应商改变时触发
    supplierChange(supplierId) {
      if (!this.$utils.isEmpty(supplierId)) {
        this.$api.sc.purchase.receiveSheet.getPaymentDate(supplierId).then(res => {
          if (res.allowModify) {
            // 如果允许修改付款日期
            if (this.$utils.isEmpty(this.formData.paymentDate)) {
              this.formData.paymentDate = res.paymentDate || ''
            }
          } else {
            // 不允许修改则按默认日期
            this.formData.paymentDate = res.paymentDate || ''
          }
          this.formData.allowModifyPaymentDate = res.allowModify
        })
      }
    },
    // 检查库存数量
    checkStockNum(row) {
      const checkArr = this.tableData.filter(item => item.productId === row.productId).map(item => item.returnNum)
      if (this.$utils.isEmpty(checkArr)) {
        checkArr.push(0)
      }
      const totalReturnNum = checkArr.reduce((total, item) => {
        const returnNum = this.$utils.isIntegerGtZero(item) ? item : 0
        return this.$utils.add(total, returnNum)
      }, 0)

      return totalReturnNum <= row.stockNum
    }
  }
}
</script>
<style>
</style>
